/* -*- indent-tabs-mode:T; c-basic-offset:8; tab-width:8; -*- vi: set ts=8:
 * $Id: fast_matrix.c,v 1.1 2004/09/12 03:40:39 poine Exp $
 *
 * Optimized matrix math library.  This is messy for speed, not
 * for readability.
 *
 * (c) 2003 Trammell Hudson <hudson@rotomotion.com>
 *
 *************
 *
 *  This file is part of the autopilot onboard code package.
 *  
 *  Autopilot is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *  
 *  Autopilot is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with Autopilot; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include <mat/fast_matrix.h>
#include <stdint.h>


static inline int
is_zero(
	const double *		dp
)
{
	const uint32_t *	ip = (uint32_t*) dp;

	return ip[0] == 0 && ip[1] == 0;
}


/*
 * mulNxMxP will perform the following operations:
 *
 * 	OUT  = A * B
 *	OUT += A * B
 *	OUT -= A * B
 *	OUT  = A * B'
 *	OUT += A * B'
 *	OUT -= A * B'
 */
void
multNxMxP(
	void *			OUT_ptr,
	const void *		A_ptr,
	const void *		B_ptr,
	int			n,
	int			m,
	int			p,
	int			add,
	int			transpose_B
)
{
	int			i;
	int			j;
	int			k;

	double *		OUT = OUT_ptr;
	const double *		A = A_ptr;
	const double *		B = B_ptr;


	for( i=0 ; i<n ; i++ )
	{
		const double *		A_i = A + i * m;
		double *		O_i = OUT + i * p;

		for( j=0 ; j<p ; j++ )
		{
			double			s = 0;
			double *		O_i_j = O_i + j;

			for( k=0 ; k<m ; k++ )
			{
				const double *		a = A_i + k;
				const double *		b;

#ifdef NO_FPU
				if( is_zero( a ) )
					continue;
#endif

				if( transpose_B )
					b = B + j * m + k;
				else
					b = B + k * p + j;

#ifdef NO_FPU
				if( is_zero( b ) )
					continue;
#endif

				s += *a * *b;
			}


			if( add == 0 )
				*O_i_j = s;
			else
			if( add > 0 )
				*O_i_j += s;
			else
				*O_i_j -= s;
		}
	}
}
